﻿/**
 * 程序名称：任务执行框架JJYChengTaskWinForm-
 * 作者：jjycheng
 * 博客：https://blog.csdn.net/cplvfx
 * gitee:https://gitee.com/jjycheng
 **/
using Microsoft.AspNetCore.StaticFiles;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JJYChengTaskWinForm.Helper
{
    public class HttpHelper
    {
        /// <summary>
        /// 发起POST同步请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
        /// <param name="headers">填充消息头</param>        
        /// <returns></returns>
        public static string HttpPost(string url, string postData = null, string contentType = null, int timeOut = 30, Dictionary<string, string> headers = null)
        {
            Console.WriteLine($"【{DateTime.Now}】Post请求{url}");
            postData ??= "";
            using HttpClient client = new HttpClient();
            client.Timeout = new TimeSpan(0, 0, timeOut);
            if (headers != null)
            {
                foreach (var header in headers)
                    client.DefaultRequestHeaders.Add(header.Key, header.Value);
            }
            using HttpContent httpContent = new StringContent(postData, Encoding.UTF8);
            if (contentType != null)
                httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);

            HttpResponseMessage response = client.PostAsync(url, httpContent).Result;
            return response.Content.ReadAsStringAsync().Result;
        }

        /// <summary>
        /// 发起POST异步请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
        /// <param name="headers">填充消息头</param>        
        /// <returns></returns>
        public static async Task<string> HttpPostAsync(string url, string postData = null, string contentType = null, int timeOut = 30, Dictionary<string, string> headers = null)
        {
            postData ??= "";
            using HttpClient client = new HttpClient();
            client.Timeout = new TimeSpan(0, 0, timeOut);
            if (headers != null)
            {
                foreach (var header in headers)
                    client.DefaultRequestHeaders.Add(header.Key, header.Value);
            }
            using HttpContent httpContent = new StringContent(postData, Encoding.UTF8);
            if (contentType != null)
                httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);

            HttpResponseMessage response = await client.PostAsync(url, httpContent);
            return await response.Content.ReadAsStringAsync();
        }

        /// <summary>
        /// 发起 POST 请求（支持 form-data 混合上传：文件 + 文本字段）
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="file">文件流 + 文件名+字段名）</param>
        /// <param name="formData">文本字段（如 new { id = 1, userName = "小明" }）</param>
        /// <param name="timeOut">超时时间（秒）</param>
        /// <param name="headers">请求头</param>
        /// <returns>响应结果</returns>
        public static async Task<string> HttpPostFormDataAsync(
            string url,
            (Stream Content, string FileName, string ParamName)? file = null,
            object formData = null,
            int timeOut = 30,
            Dictionary<string, string> headers = null)
        {
            using HttpClient client = new HttpClient();
            client.Timeout = TimeSpan.FromSeconds(timeOut);

            // 添加请求头（跳过 Content-Type，由 MultipartFormDataContent 自动处理）
            if (headers != null)
            {
                foreach (var header in headers)
                {
                    if (string.Equals(header.Key, "Content-Type", StringComparison.OrdinalIgnoreCase))
                        continue; // 避免冲突，由 multipart 自动设置
                    client.DefaultRequestHeaders.TryAddWithoutValidation(header.Key, header.Value);
                }
            }

            // 构建 form-data 内容
            var multipartContent = new MultipartFormDataContent();

            // 1. 添加文件字段（file）
            if (file.HasValue)
            {
                var (stream, fileName, ParamName) = file.Value;
                var streamContent = new StreamContent(stream);
                // 自动识别文件 MIME 类型（推荐）
                var mimeType = GetContentType(fileName);
                streamContent.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(mimeType);

                multipartContent.Add(streamContent, ParamName, fileName); // 字段名固定为 "file"
            }

            // 2. 添加普通文本字段（id/userName/userAge 等）
            if (formData != null)
            {
                // 反射解析 object 的属性为表单字段
                var properties = formData.GetType().GetProperties();
                foreach (var prop in properties)
                {
                    var value = prop.GetValue(formData)?.ToString();
                    if (value == null) continue;

                    var stringContent = new StringContent(value, Encoding.UTF8);
                    // 文本字段无需设置 Content-Type，默认就是 text/plain
                    multipartContent.Add(stringContent, prop.Name);
                }
            }

            // 发送请求
            using HttpResponseMessage response = await client.PostAsync(url, multipartContent);
            response.EnsureSuccessStatusCode();
            return await response.Content.ReadAsStringAsync();
        }

        /// <summary>根据文件名获取 MIME 类型</summary>
        private static string GetContentType(string fileName)
        {
            var provider = new FileExtensionContentTypeProvider();
            return provider.TryGetContentType(fileName, out var contentType)
                ? contentType
                : "application/octet-stream";
        }

        /// <summary>
        /// 发起GET同步请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="headers"></param>
        /// <returns></returns>
        public static string HttpGet(string url, Dictionary<string, string> headers = null)
        {
            Console.WriteLine($"【{DateTime.Now}】Get请求{url}");
            using HttpClient client = new HttpClient();
            if (headers != null)
            {
                foreach (var header in headers)
                    client.DefaultRequestHeaders.Add(header.Key, header.Value);
            }
            else
            {
                client.DefaultRequestHeaders.Add("ContentType", "application/x-www-form-urlencoded");
                client.DefaultRequestHeaders.Add("UserAgent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
            }
            try
            {
                HttpResponseMessage response = client.GetAsync(url).Result;
                return response.Content.ReadAsStringAsync().Result;
            }
            catch (Exception ex)
            {
                throw new Exception($"[Http请求出错]{url}|{ex.Message}");
            } 
        }

        /// <summary>
        /// 发起GET异步请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="headers"></param>
        /// <returns></returns>
        public static async Task<string> HttpGetAsync(string url, Dictionary<string, string> headers = null)
        {
            using HttpClient client = new HttpClient();
            if (headers != null)
            {
                foreach (var header in headers)
                    client.DefaultRequestHeaders.Add(header.Key, header.Value);
            }
            HttpResponseMessage response = await client.GetAsync(url);
            return await response.Content.ReadAsStringAsync();
        }

        /// <summary>
        /// 发起Put同步请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
        /// <param name="headers">填充消息头</param>        
        /// <returns></returns>
        public static string HttpPut(string url, string postData = null, string contentType = null, int timeOut = 30, Dictionary<string, string> headers = null)
        {
            postData ??= "";
            using HttpClient client = new HttpClient();
            client.Timeout = new TimeSpan(0, 0, timeOut);
            if (headers != null)
            {
                foreach (var header in headers)
                    client.DefaultRequestHeaders.Add(header.Key, header.Value);
            }
            using HttpContent httpContent = new StringContent(postData, Encoding.UTF8);
            if (contentType != null)
                httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);

            HttpResponseMessage response = client.PutAsync(url, httpContent).Result;
            return response.Content.ReadAsStringAsync().Result;
        }
    }

}
